package team.bluepen.supermarket.common;

import java.util.function.Function;

/**
 * @author RollW
 */
public class MessagePackage<D> {
    private final ErrorCode errorCode;
    private final String message;
    private final D data;

    public MessagePackage(ErrorCode code, D data) {
        this(code, code.toString(), data);
    }

    public MessagePackage(ErrorCode errorCode, String message, D data) {
        this.errorCode = errorCode;
        this.message = message;
        this.data = data;
    }
    public HttpResponseBody<D> toResponseBody() {
        if (errorCode.getState()) {
            return HttpResponseBody.success(message(), data());
        }
        return HttpResponseBody.failure(message(), errorCode(), data());
    }

    public <T> HttpResponseBody<T> toResponseBody(Function<D, T> typeTrans) {
        if (errorCode.getState()) {
            return HttpResponseBody.success(message(), typeTrans.apply(data()));
        }
        return HttpResponseBody.failure(message(), errorCode(), typeTrans.apply(data()));
    }

    public ErrorCode errorCode() {
        return errorCode;
    }

    public String message() {
        return message;
    }

    public D data() {
        return data;
    }
}

